<?php

namespace Beerus\Modules\WikiRanking\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\wiki\WikiRankingCategory as mWikiRankingCategory;
use Biz\model\wiki\WikiRankingConfig as mWikiRankingConfig;
use Doraemon\model\Category as mCategory;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class RankingConfigController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    /**
     * 一级榜单列表
     * @param Content $content
     * @return Content
     */
    public function list(Content $content)
    {
        $rankingList = mWikiRankingConfig::selectByWhere(['pid' => 0, 'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL, 'ORDER' => ['sort' => 'ASC']]);
        $ids = $rankingList ? array_column($rankingList, 'id') : [];
        $secondList = [];
        if ($ids) {
            $secondArr = mWikiRankingConfig::selectByWhere(['pid' => $ids, 'config_state' => mWikiRankingConfig::CONFIG_STATE_SHOW]);
            foreach ($secondArr as $row) {
                $secondList[$row['pid']][] = $row;
            }
        }
        $list = [];
        foreach ($rankingList as $row) {
            $row['icon_url'] = $row['icon'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['icon'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $row['cover_img_url'] = $row['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $row['second_list'] = isset($secondList[$row['id']]) ? $secondList[$row['id']] : [];
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        $categoryGird = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id')->sort();
            $grid->column('ranking_name', '一级榜单名');
            $grid->column('config_state', '隐藏')->switchToggle([
                'on' => [
                    'value' => mWikiRankingConfig::CONFIG_STATE_SHOW,
                    'text' => '展示'
                ],
                'off' => [
                    'value' => mWikiRankingConfig::CONFIG_STATE_NORMAL,
                    'text' => '隐藏'
                ]
            ]);
            $grid->column('second_list', '二级榜单')->display(function () {
                $format = [];
                if ($this->second_list) {
                    foreach ($this->second_list as $row) {
                        $format[] = "<a href='/admin/wikiRanking/index/{$row['pid']}/edit/{$row['id']}/edit'>{$row['id']}-{$row['ranking_name']}</a>";
                    }
                }
                return $format;
            })->label('default');
        });
        return $content->header('榜单分类管理')->row($categoryGird);
    }

    /**
     * 一级榜单编辑页
     * @param Content $content
     * @param int $firstId
     * @return Content
     */
    public function firstEdit(Content $content, $firstId = 0)
    {
        $tab = new Tab();
        //基础信息
        $firstRankingInfo = [];
        if ($firstId) {
            $firstRankingInfo = mWikiRankingConfig::getByWhere(['id' => $firstId]);
        }
        $basicForm = new Form($firstRankingInfo);
        $basicForm->text('ranking_name', '一级榜单名')->rules('required|min:1');
        $basicForm->action('/admin/wikiRanking/index/' . $firstId . '/save');
        $tab->add('基础信息', $basicForm);
        if ($firstId) {
            $secGird = $this->secondRankingGrid($firstId);
            $tab->add('二级榜单', $secGird);
        }
        $content->header('一级榜单配置' . ($firstId ? "-" . $firstRankingInfo['ranking_name'] : ""))
            ->breadcrumb([
                'text' => '榜单分类管理',
                'url' => '/wikiRanking/index'
            ], ['text' => '一级榜单配置'])
            ->row($tab);
        return $content;
    }

    /**
     * 保存一级榜单信息
     * @param Request $request
     * @param int $firstId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveFirst(Request $request, $firstId = 0)
    {
        $data = [];
        $data['ranking_name'] = trim($request->input('ranking_name'));
        $data['admin_id'] = Admin::user()->id;
        $data['deep'] = 1;
        try {
            if ($firstId) {
                mWikiRankingConfig::updateData($data, ['id' => $firstId]);
            } else {
                $firstId = mWikiRankingConfig::insertData($data);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/wikiRanking/index')->with(compact('success'));
    }


    /**
     * 二级榜单编辑页
     * @param Content $content
     * @param $firstId
     * @param int $secondId
     * @return Content
     */
    public function childRankingEdit(Request $request, Content $content, $firstId, $secondId = 0)
    {
        $tab = new Tab();
        $secondInfo = ['cate_ids' => []];
        if ($secondId) {
            $secondInfo = mWikiRankingConfig::getByWhere(['id' => $secondId]);
            $catIds = mWikiRankingCategory::selectByWhere(['ranking_id' => $secondId, 'cate_state' => mWikiRankingCategory::CAT_STATE_NORMAL], 'cate_id');
            $secondInfo['cate_ids'] = $catIds;
        }
        $lastCategories = mCategory::getSelectLastStageCate(2);

        $basicForm = new Form($secondInfo);
        $basicForm->hidden('id');
        $basicForm->hidden('pid')->default($firstId);
        $basicForm->text('ranking_name', '二级榜单名');
        $basicForm->multipleSelect('cate_ids', '关联后台类目')->options($lastCategories);
        $basicForm->imgUpload('icon', 'icon');
        $basicForm->imgUpload('cover_img', '分享图片');
        $basicForm->action('/admin/wikiRanking/index/' . $firstId . '/edit/' . $secondId . '/save');
        $content->header('二级榜单配置' . ($secondInfo ? "-" . $secondInfo['ranking_name'] : ""))
            ->breadcrumb([
                'text' => '榜单分类管理',
                'url' => '/wikiRanking/index'
            ], [
                'text' => '一级榜单编辑',
                'url' => '/wikiRanking/index/' . $firstId . '/edit'
            ], ['text' => '二级榜单配置']);

        $tab->add('基础信息', $basicForm);
        $content->row($tab);
        return $content;
    }

    /**
     * 保存二类榜单
     * @param Request $request
     * @param int $firstId
     * @param int $secondId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveSecond(Request $request, $firstId, $secondId = 0)
    {
        $data = [
            'ranking_name' => trim($request->input('ranking_name', '')),
            'icon' => $request->input('icon'),
            'cover_img' => $request->input('cover_img'),
            'pid' => $firstId,
            'deep' => 2,
            'admin_id' => Admin::user()->id
        ];
        $catIds = $request->input('cate_ids');
        $catIds = array_filter($catIds);
        try {
            if ($secondId) {
                mWikiRankingConfig::updateData($data, ['id' => $secondId]);
                $cateList = mWikiRankingCategory::selectByWhere(['ranking_id' => $secondId]);
                $allCateIds = $cateList ? array_column($cateList, 'cate_id') : [];
                $cateList = $cateList ? array_column($cateList, null, 'cate_id') : [];
                $delCateIds = array_diff($allCateIds, $catIds);
                if ($delCateIds) {
                    mWikiRankingCategory::updateData(['cate_state' => mWikiRankingCategory::CAT_SATE_DEL], ['cate_id' => $delCateIds, 'ranking_id' => $secondId]);
                }
                foreach ($catIds as $catId) {
                    if (isset($cateList[$catId])) {
                        mWikiRankingCategory::updateData(['cate_state' => mWikiRankingCategory::CAT_STATE_NORMAL], ['cate_id' => $catId, 'ranking_id' => $secondId]);
                    } else {
                        mWikiRankingCategory::insertData([
                            'ranking_id' => $secondId,
                            'cate_state' => mWikiRankingCategory::CAT_STATE_NORMAL,
                            'cate_id' => $catId,
                        ]);
                    }
                }
            } else {
                $info = mWikiRankingConfig::getByWhere(['pid' => $firstId, 'ranking_name' => $data['ranking_name']]);
                if ($info) {
                    $secondId = $info['id'];
                    $data['config_state'] = mWikiRankingConfig::CONFIG_STATE_NORMAL;
                    mWikiRankingConfig::updateData($data, ['id' => $info['id'], 'pid' => $firstId]);
                } else {
                    $secondId = mWikiRankingConfig::insertData($data);
                }
                foreach ($catIds as $catId) {
                    mWikiRankingCategory::insertData([
                        'ranking_id' => $secondId,
                        'cate_state' => mWikiRankingCategory::CAT_STATE_NORMAL,
                        'cate_id' => $catId,
                    ]);
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/wikiRanking/index/' . $firstId . '/edit')->with(compact('success'));
    }

    /**
     * 榜单排序
     * @param Request $request
     */
    public function sort(Request $request, $firstId = 0)
    {
        $sort = $request->input('sort', []);
        foreach ($sort as $key => $val) {
            mWikiRankingConfig::updateData(['sort' => $val], ['id' => $key]);
        }
    }

    public function relate(Request $request, Content $content, $firstId, $secondId)
    {
        $info = mWikiRankingConfig::getByWhere(['id' => $secondId]);
        $allSecondArr = mWikiRankingConfig::selectByWhere(['deep' => 2, 'pid[>]' => 0, 'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL], ['id', 'ranking_name']);
        $secondOption = [];
        foreach ($allSecondArr as $row) {
            if ($row['id'] != $secondId) {
                $secondOption[$row['id']] = $row['ranking_name'];
            }
        }
        $from = new Form($info);
        $from->text('id', '二级榜单ID')->readonly();
        $from->text('ranking_name', '二级榜单名')->rules('required|min:1')->readonly();
        $from->multipleSelect('relate_id', '关联二级榜单')->options($secondOption);
        $from->action('/admin/wikiRanking/index/' . $firstId . '/' . $secondId . '/relate/save');
        $content->header('二级榜单关联')
            ->breadcrumb([
                'text' => '一级榜单配置',
                'url' => '/wikiRanking/index/' . $firstId . '/edit',
            ], ['text' => '二级榜单关联'])
            ->row($from);
        return $content;
    }

    public function relateSave(Request $request, $firstId, $secondId)
    {
        $relateId = $request->input('relate_id', '');
        $relateId = $relateId ? implode(',', array_filter($relateId)) : '';
        try {
            $info = mWikiRankingConfig::getByWhere(['id' => $secondId]);
            if (!$secondId || empty($info)) {
                throw new \Exception('不存在的榜单');
            }
            $res = mWikiRankingConfig::updateData(['relate_id' => $relateId], ['id' => $secondId]);
            if (!$res) {
                throw new \Exception('保存数据失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/wikiRanking/index/' . $firstId . '/edit')->with(compact('success'));
    }

    /**
     * 二级榜单列表
     * @param $firstId 一级榜单id
     * @return string
     */
    private function secondRankingGrid($firstId)
    {
        $allFirstArr = mWikiRankingConfig::selectByWhere(['pid' => 0, 'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL], ['id', 'ranking_name']);
        $firstOption = [];
        foreach ($allFirstArr as $row) {
            $firstOption[$row['id']] = $row['ranking_name'];
        }
        $list = [];
        $rankingList = mWikiRankingConfig::selectByWhere(['pid' => $firstId, 'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL, 'ORDER' => ['sort' => 'ASC']]);
        $ids = $rankingList ? array_column($rankingList, 'id') : [];
        $rankingList = $rankingList ? array_column($rankingList, null, 'id') : [];
        $rankingCateArr = mWikiRankingCategory::selectByWhere(['ranking_id' => $ids, 'cate_state' => mWikiRankingCategory::CAT_STATE_NORMAL]);
        $rankingCateList = [];
        $categoryIds = [];
        if ($rankingCateArr) {
            foreach ($rankingCateArr as $row) {
                $categoryIds[] = $row['cate_id'];
                $rankingCateList[$row['ranking_id']][] = $row;
            }
        }
        $categoryIds = array_unique($categoryIds);
        $cateList = mCategory::selectByWhere(['id' => $categoryIds]);
        $cateList = $cateList ? array_column($cateList, null, 'id') : [];
        $relateIds = [];
        foreach ($rankingList as $id => $row) {
            $relIds = $row['relate_id'] ? explode(',', $row['relate_id']) : [];
            $relateIds = array_merge($relateIds, $relIds);
        }
        $relateIds = array_unique($relateIds);
        $relateIds = array_diff($relateIds, $ids);
        $otherRelateList = mWikiRankingConfig::selectByWhere(['id' => $relateIds], ['id', 'ranking_name']);
        $otherRelateList = $otherRelateList ? array_column($otherRelateList, null, 'id') : [];
        foreach ($rankingList as $id => $row) {
            if (isset($rankingCateList[$id])) {
                foreach ($rankingCateList[$id] as $rankingCateInfo) {
                    if (isset($cateList[$rankingCateInfo['cate_id']])) {
                        $row['cate_list'][] = $cateList[$rankingCateInfo['cate_id']];
                    }
                }
            }
            $row['icon_url'] = $row['icon'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['icon'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $row['cover_img_url'] = $row['cover_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $row['cover_img'], ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            $relateList = $row['relate_id'] ? explode(',', $row['relate_id']) : [];
            $row['relate_list'] = [];
            foreach ($relateList as $relateId) {
                if (isset($rankingList[$relateId]) && $rankingList[$relateId]) {
                    $row['relate_list'][] = $rankingList[$relateId]['ranking_name'];
                } else if (isset($otherRelateList[$relateId]) && $otherRelateList[$relateId]) {
                    $row['relate_list'][] = $otherRelateList[$relateId]['ranking_name'];
                }
            }
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        return Admin::grid($gridModel, function (Grid $grid) use ($firstId, $firstOption) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id')->sort();
            $grid->column('ranking_name', '二级榜单名称');
            $grid->column('pid', '一级榜单')->radio($firstOption);
            $grid->column('icon_url', 'icon')->image(100, 100);
            $grid->column('cover_img_url', '分享图片')->image(100, 100);
            $grid->column('config_state', '隐藏')->switchToggle([
                'on' => [
                    'value' => mWikiRankingConfig::CONFIG_STATE_SHOW,
                    'text' => '展示'
                ],
                'off' => [
                    'value' => mWikiRankingConfig::CONFIG_STATE_NORMAL,
                    'text' => '隐藏'
                ]
            ]);
            $grid->column('cate_list', '关联后台类目')->display(function () {
                $format = [];
                if ($this->cate_list) {
                    foreach ($this->cate_list as $cate) {
                        $format[] = "{$cate['deep']}级-{$cate['cate_name']}";
                    }
                }
                return $format;
            })->badge("gray");
            $grid->column('relate_id', '关联榜单')->display(function () use ($firstId) {
                $format = [];
                if ($this->relate_list) {
                    foreach ($this->relate_list as $relate_name) {
                        $format[] = "<a href='" . url('/admin/wikiRanking/index/' . $firstId . '/' . $this->id . '/relate') . "'>{$relate_name}</a>";
                    }
                } else {
                    $format[] = "<a href='" . url('/admin/wikiRanking/index/' . $firstId . '/' . $this->id . '/relate') . "'>去关联</a>";
                }
                return $format;
            })->badge("gray");
        })->render();

    }


    public function delConfig($firstId, $secondId = 0)
    {
        $configState = mWikiRankingConfig::CONFIG_STATE_DEL;
        if ($secondId) {//删除 二级榜单
            mWikiRankingConfig::updateData(['config_state' => $configState], ['id' => $secondId]);
        } else {//删除 一级榜单 同时删除二级榜单
            mWikiRankingConfig::updateData(['config_state' => $configState], ['id' => $firstId]);
            mWikiRankingConfig::updateData(['config_state' => $configState], ['pid' => $firstId, 'config_state[!]' => mWikiRankingConfig::CONFIG_STATE_DEL]);
        }
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }

    public function switchConfigState(Request $request, $firstId, $secondId = 0)
    {
        $data = $request->all();
        if (isset($data['config_state'])) {
            $configState = ($data['config_state'] == 'off') ? mWikiRankingConfig::CONFIG_STATE_NORMAL : mWikiRankingConfig::CONFIG_STATE_SHOW;
            if ($secondId) {//显示不显示 二级榜单
                mWikiRankingConfig::updateData(['config_state' => $configState], ['id' => $secondId]);
            } else {//显示不显示 一级榜单
                if ($configState == mWikiRankingConfig::CONFIG_STATE_NORMAL) {//一级不显示，二级也不显示
                    mWikiRankingConfig::updateData(['config_state' => $configState], ['id' => $firstId]);
                    mWikiRankingConfig::updateData(['config_state' => $configState], ['pid' => $firstId, 'config_state' => mWikiRankingConfig::CONFIG_STATE_SHOW]);
                } else {
                    mWikiRankingConfig::updateData(['config_state' => $configState], ['id' => $firstId]);
                }
            }
        } else if ($secondId && isset($data['_edit_inline']) && $data['_edit_inline'] && isset($data['pid']) && $data['pid']) {//二级分类移动到一级分类
            mWikiRankingConfig::updateData(['pid' => $data['pid']], ['id' => $secondId]);
        } else {
            return response()->json(['stauts' => false, 'message' => '参数错误']);
        }
        return response()->json([
            'status' => true,
            'message' => "修改成功",
        ]);
    }

}
